package com.wondertek.mist.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.Handler;

import com.wondertek.mist.Utils;
import com.wondertek.mist.po.VersionPo;

public class ApkUpdate {

	
	public static boolean isIntalledApk(final Context ctx,final String packageName) {
		final List<PackageInfo> packages = ctx.getPackageManager().getInstalledPackages(0);
		boolean hasInstalled = false;
		for (int i = 0; i < packages.size(); i++) {
			PackageInfo packageInfo  = packages.get(i);;
			if(packageInfo!=null && packageInfo.packageName.equals(packageName)){
				hasInstalled = true;
				break;
			}
		} 
		return hasInstalled;
	}
	
	public static void install(Context context, String path) {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(new File(path)), "application/vnd.android.package-archive");
		context.startActivity(intent);
	}
	
	/**
	 * 更新 新版本的Apk程序
	 */
	public static void startUpdateProgress(final Context ctx, final VersionPo versionPo, Handler handler) {		
		StringBuffer sb = new StringBuffer();
		String[] hintContent = versionPo.getVersion_features();
		for(int i=0;i<hintContent.length;i++){
			sb.append(hintContent[i]+"\n");
		}
		if("1".equals(versionPo.getVersion_result())){
			new AlertDialog.Builder(ctx).setTitle("软件更新").setMessage(sb.toString())
			.setPositiveButton("确定",new PositiveClickListener(ctx,versionPo, handler))
			.setNegativeButton("取消", new NegativeClickListener(ctx,versionPo, handler))
			.show();
		}else{
			new AlertDialog.Builder(ctx).setTitle("软件更新").setMessage(sb.toString())
			.setPositiveButton("确定",new PositiveClickListener(ctx,versionPo, handler))			
			.show();
		}				
	}
	
	public static class PositiveClickListener implements DialogInterface.OnClickListener{      
		private final Context ctx;
		private final VersionPo versionPo;
		private Handler handler;
        
		public PositiveClickListener(Context ctx, VersionPo versionPo, Handler handler) {
			super();
			this.ctx = ctx;
			this.versionPo = versionPo;
			this.handler = handler;
		}

		@Override
		public void onClick(DialogInterface dialog, int which) {
			new AsyncTask<Void, Void, String>() {							
				private DownloadProgress dp;
				@Override
				protected void onPreExecute() {
					dp = new DownloadProgress(ctx);
					dp.show();
				}

				@Override
				protected String doInBackground(Void... params) {
					try {
						String downloadUrl =versionPo.getVersion_url();
						return downloadNewVersionApk(downloadUrl,dp);
					} catch (Exception e) {
						
					}
					return "";
				}

				@Override
				protected void onPostExecute(final String downloadPath) {	
					if (dp != null) {
						dp.setFinish();
						dp.dismiss();
					} 
					if (!StringUtils.isEmpty(downloadPath)) {
						install(ctx, downloadPath);
					}else{
						handler.sendEmptyMessage(Utils.MSG_TO_MIST);
	//					StartActivity.toMistAction(ctx);	
					}
				}
			}.execute();
			dialog.dismiss();
		}
	}

	public static class NegativeClickListener implements DialogInterface.OnClickListener{      
		private final Context ctx;
		private final VersionPo versionPo;
		private Handler handler;
        
		public NegativeClickListener(Context ctx, VersionPo versionPo, Handler handler) {
			super();
			this.ctx = ctx;
			this.versionPo = versionPo;
			this.handler = handler;
		}

		@Override
		public void onClick(DialogInterface dialog, int which) {
	//		StartActivity.toMistAction(ctx);	
			handler.sendEmptyMessage(Utils.MSG_TO_MIST);
			dialog.dismiss();
		}
	}


	/** 新的apk 下载到 sdcard目录下 ,返回下载回来的apk存放的位置全路径 **/
	public static String downloadNewVersionApk(final String download_url,final DownloadProgress downloadProgress) {
		HttpClient client = new DefaultHttpClient();
		HttpGet get = new HttpGet(download_url);
		InputStream is = null;
		String returnDownloadFileName = ""; 
		FileOutputStream fileOutputStream = null;
		try {
			HttpResponse response = client.execute(get);
			HttpEntity entity = response.getEntity();
			if(entity!=null) {
				long length = entity.getContentLength();
				if(length>=1024){				
					downloadProgress.refresh((int) length, 0);
					is = entity.getContent();
					if (is != null) {
						File file = new File(Environment.getExternalStorageDirectory(), ResourcesDowner.getFileName(download_url));
						returnDownloadFileName = file.getPath();
						fileOutputStream = new FileOutputStream(file);
						byte[] buf = new byte[2048];
						int len = -1;
						int byteReadCount= 0 ; //共读取的字节数量
						while ((len = is.read(buf)) != -1) {
							byteReadCount +=len;
							fileOutputStream.write(buf, 0, len);
							downloadProgress.refresh(byteReadCount, 1);
						}
						fileOutputStream.flush();
					}
				}
			}
		}catch (Exception e) {			
		} finally {
			try {
				if (fileOutputStream != null)
					fileOutputStream.close();
				if (is != null)
					is.close();
				client.getConnectionManager().shutdown(); //必须关闭连接
			} catch (IOException ex) {
			}
		}
		return returnDownloadFileName;
	}
	
}
